// pages/student/hallRoom/hallRoom.js
import {
    ajaxPost,
    showToast,
    generateRichTextNode,
    Time,
} from '../../../utils/util.js'
var app = getApp();
import SDK from "../../../IMJS/NIM_Web_SDK_weixin_v6.2.0";
Page({

    /**
     * 页面的初始数据
     */
    data: {
        WEBURL: app.globalData.WEBURL, // 背景图域名
        showBack: false, // 分享进来的 返回按钮是否显示

        companyListShow: false, // 更多企业是否展示 false =》不展示 true =》展示
        hallId: '', // 大厅id
        hallRoomId: '', // 房间id
        hallNewsArr: [], // 房间聊天室信息储存
        companyListSource: [], // 公司列表
        noticeShow: true, // 公告是否显示 false=>不显示

        popupShow: false, // 弹窗里面是否显示 false=>不显示
        recruitShow: false, // 招聘详情是否显示 false=>不显示

        emojiShow: false, // 表情是否显示 false=>不显示
        inputValue: '', // 聊天输入框

        popupVal: 2, // 弹窗里面显示第几个
        companySource: {}, // 弹窗公司详情
        recruitSource: {}, // 招聘列表
        companyHot: [], // 推荐公司
        meetingSource: {}, // 招聘会信息
        focusFlag: false, //控制输入框失去焦点与否
        scrollTop: 0, // 聊天内容 高度位置
        scrollHeight: 0, // 聊天内容 总共高度 
        account: app.globalData.account,

        isPerfectInfo: false,
        inviteSource: [], // 企业邀请列表 
        formShow: true,
    },
    /**
     * 控制更多企业列表是否显示
     */
    selectcompanyListShow(e) {
        if (e.currentTarget.dataset.show == 'true') {
            this.setData({
                companyListShow: true
            })
            this.getRoomInfo();
        } else {
            this.setData({
                companyListShow: false
            })
        }
    },
    companySelect(e) {
        let data = e.currentTarget.dataset.data
        if (!data) {
            this.setData({
                popupVal: 2,
                recruitShow: false,
                popupShow: false
            })
            return;
        }
        this.getCompanyInfo(data.company_uid)

    },
    goSmallRoom() {
        let roomInfo = this.data.companySource
        console.log(roomInfo);
        var startTime = new Date(this.data.meetingSource.start_time);
        var currentTime = Date.parse(new Date());
        if (Date.parse(startTime) > currentTime) {
            showToast('text', '招聘会暂未开场');
            return;
        }
        if (!this.isPerfectInfo) {
            wx.showModal({
                title: '操作提示',
                content: '简历还没有完善，请完善简历后重试',
                success(res) {
                    if (res.confirm) {
                        wx.navigateTo({
                            url: '/pages/student/mine/mine'
                        })
                    } else if (res.cancel) {
                        console.log('用户点击取消')
                    }
                }
            })
            return;
        }
        let data = {
            token: wx.getStorageSync("token"),
            company_uid: roomInfo.uid,
        };
        ajaxPost("/company/companyInfo", data, (res) => {
            if (res.code == 0) {
                if (res.data.company_data.is_online == 0) {
                    showToast('text', '招聘者暂时不在，请稍后再试');
                    return;
                }
                if (res.data.student_count >= 10) {
                    showToast('text', '该房间以爆满，请选择其他房间重试');
                    return;
                }
                this.setData({
                    popupVal: 2,
                    popupShow: false
                })
                wx.navigateTo({
                    url: '/pages/student/smallRoom/smallRoom?id=' + this.data.hallId + '&hallRoomId=' + this.data.hallRoomId + '&companyid=' + roomInfo.uid
                })

            } else {
                showToast('text', res.msg)
            }
        });
    },

    /**
     * 获取企业信息
     */
    getCompanyInfo(id) {
        let that = this
        let data = {
            token: wx.getStorageSync("token"),
            company_uid: id,
        };
        ajaxPost("/company/companyInfo", data, function (res) {
            if (res.code == 0) {
                that.setData({
                    popupShow: true,
                    companySource: res.data.company_data,
                    recruitSource: res.data.position_list,
                })
            } else {
                showToast('text', res.msg)
            }
        });
    },

    /**
     *  详情内投递简历
     * @param {*} e 
     */
    workSend(e) {
        const {
            is
        } = e.target.dataset
        const {
            workSource
        } = this.data
        if (is == 1) {
            showToast('text', '已经投递过了');
            return;
        }
        if (!this.isPerfectInfo) {
            wx.showModal({
                title: '操作提示',
                content: '简历还没有完善，请完善简历后重试',
                success(res) {
                    if (res.confirm) {
                        wx.navigateTo({
                            url: '/pages/student/mine/mine'
                        })
                    } else if (res.cancel) {
                        console.log('用户点击取消')
                    }
                }
            })
            return;
        }
        let data = {
            token: wx.getStorageSync('token'),
            position_id: workSource.id
        }
        ajaxPost('/company/sendresume', data, (res) => {
            if (res.code == 0) {
                this.getCompanyInfo(workSource.uid)
                let newWorkSource = workSource
                newWorkSource.is_send_resume = 1
                this.setData({
                    workSource: newWorkSource
                })
                showToast('text', '投递成功');
            } else {
                showToast('text', res.msg);
            }
        })
    },
    /**
     * 投递简历
     */
    send(e) {
        let index = e.target.dataset.index
        let resume = this.data.recruitSource[index]
        if (resume.is_send_resume == 1) {
            showToast('text', '已经投递过了');
            return;
        }
        if (!this.isPerfectInfo) {
            wx.showModal({
                title: '操作提示',
                content: '简历还没有完善，请完善简历后重试',
                success(res) {
                    if (res.confirm) {
                        wx.navigateTo({
                            url: '/pages/student/mine/mine'
                        })
                    } else if (res.cancel) {
                        console.log('用户点击取消')
                    }
                }
            })
            return;
        }
        let data = {
            token: wx.getStorageSync('token'),
            position_id: resume.id
        }
        ajaxPost('/company/sendresume', data, (res) => {
            if (res.code == 0) {
                let newresume = this.data.recruitSource
                newresume[index].is_send_resume = 1
                this.setData({
                    recruitSource: newresume
                })
                showToast('text', '投递成功');
            } else {
                showToast('text', res.msg);
            }
        })

    },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if (app.globalData.fromShowVal) {
            this.setData({
                formShow: false,
            })
        }
        let ajaxData = {
            token: wx.getStorageSync('token'),
            meeting_id: options.id
        }
        ajaxPost('/meeting/followmeeting', ajaxData, (res) => {})

        if (options.type == 'share') {
            this.setData({
                showBack: true
            })
        }
        wx.setKeepScreenOn({
            keepScreenOn: true
        })
        // 设置 scroll-view高度
        let windowHeight = wx.getSystemInfoSync().windowHeight // 屏幕的高度
        let windowWidth = wx.getSystemInfoSync().windowWidth // 屏幕的宽度
        // ? id = 66 & roomid = 104714976
        this.setData({
            hallId: options.id,
            hallRoomId: options.roomid,
            scrollHeight: windowHeight * 750 / windowWidth - 766 - 30,
            companyListHeight: windowHeight * 750 / windowWidth - 92
        })

    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.getHeart();
        this.Heart = setInterval(() => {
            this.getHeart();
        }, 5000);
        /**
         * 获取个人信息是否完善
         */
        let data = {
            token: wx.getStorageSync("token"),
        }
        ajaxPost("/authuser/myInfo", data, (res) => {
            if (res.code == 0) {
                console.log(!res.data.user_info.resume_image);
                if (!res.data.user_info.resume_image) {
                    this.isPerfectInfo = false
                } else {
                    this.isPerfectInfo = true
                }
            } else {
                showToast('text', res.msg);
            }
        });
        this.hallRoomConfig()
        this.getRoomInfo()
    },
    /**
     * 大厅心跳
     */
    getHeart() {
        let _this = this;
        let data = {
            token: wx.getStorageSync("token"),
            meeting_id: _this.data.hallId,
        };
        ajaxPost("/meeting/hallHeartBeat", data, res => {
            if (res.code == 0) {}
        });
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        clearInterval(this.Heart);
        clearInterval(this.noticeTime);
    },

    /**
     * 获取当前会场信息
     */
    getRoomInfo() {
        let that = this
        let data = {
            token: wx.getStorageSync("token"),
            meeting_id: this.data.hallId,
        };
        ajaxPost("/meeting/meetinginfo", data, res => {
            if (res.code == 0) {
                that.setData({
                    companyHot: res.data.company_recommend,
                    companyListSource: res.data.company_total,
                    meetingSource: res.data.meeting_data,
                })
                /**
                 * 判断是否可以弹出公告窗口
                 */
                if (that.data.noticeShow) {
                    let viewHeight;
                    wx.createSelectorQuery().selectAll('.notice').boundingClientRect(function (rect) {
                        viewHeight = rect[0].height
                        that.setData({
                            scrollHeight: that.data.scrollHeight - viewHeight
                        })
                    }).exec()

                    this.noticeTime = setTimeout(() => {
                        that.setData({
                            scrollHeight: that.data.scrollHeight + viewHeight,
                            noticeShow: false,
                        })
                    }, app.globalData.noticeTimeNum);
                }
                if (res.code == 40002) {
                    showToast('text', '招聘会已过期！');
                    setTimeout(() => {
                        wx.redirectTo({
                            url: '/pages/student/home/home',
                        })
                    }, 2000);

                }
                return;
            }
            showToast('text', res.msg)

        });
    },

    hallRoomConfig() {
        let that = this
        app.globalData.nim.getChatroomAddress({
            chatroomId: this.data.hallRoomId,
            done: getChatroomAddressDone
        });

        function getChatroomAddressDone(error, data) {
            app.globalData.hallRoom = SDK.Chatroom.getInstance({
                debug: false,
                appKey: app.globalData.appkey,
                token: app.globalData.wytoken,
                account: app.globalData.account,
                chatroomAddresses: data.address,
                chatroomId: data.chatroomId,
                onconnect: that.onChatroomConnect,
                onerror: that.onChatroomError,
                onwillreconnect: that.onChatroomWillReconnect,
                ondisconnect: that.onChatroomDisconnect,
                // 消息
                onmsgs: that.onChatroomMsgs

            });
        }
    },
    /**
     * 连接上服务器
     */
    onChatroomConnect(chatroomInfo) {
        showToast('text', '加入大厅聊天室成功')
        console.log('连接上服务器', chatroomInfo)
        console.log('app.globalData.hallRoom', app.globalData.hallRoom)
        this.getNum()

    },
    /**
     * 获取当前在线人数
     */
    getNum() {
        let that = this
        app.globalData.hallRoom.getChatroom({
            done: getChatroomDone
        });

        function getChatroomDone(error, obj) {
            console.log('获取聊天室信息' + (!error ? '成功' : '失败'), error, obj);
            if (!error) {
                console.log(obj.chatroom.onlineMemberNum);
                that.setData({
                    onlineMemberNum: obj.chatroom.onlineMemberNum
                })
            }
        }
    },
    /**
     * 发生错误
     */
    onChatroomError(error, obj) {
        clearTimeout(this.pageTimer)
        this.pageTimer = setTimeout(() => {
            wx.showToast({
                title: '连接已断开,即将返回',
                duration: 2000,
                success: function () {
                    wx.redirectTo({
                        url: '/pages/student/home/home',
                    })
                }
            })
        }, 200)
    },
    /**
     * 即将重连
     */
    onChatroomWillReconnect(obj) {
        console.log(`onwillreconnect-${app.globalData.reconnectionAttempts}`, obj);
    },
    /**
     * 已经断开连接
     */
    onChatroomDisconnect(error) {
        console.log('ondisconnect', error);
    },
    /**
     * 收到消息
     */
    onChatroomMsgs(msgs) {
        console.log('onChatroomMsgs', msgs)
        let self = this
        msgs.map(msg => {
            switch (msg.type) {
                case 'notification': {
                    if (msg.attach.type == 'memberEnter') {
                        console.log('有人加入');
                        this.getNum();
                        return;
                    }
                    if (msg.attach.type == 'memberExit') {
                        console.log('有人加入');
                        this.getNum();
                        return;
                    }
                    self.addNotificationToRender(msg)
                    break
                }
                case 'text': {
                    self.addTextToRender(msg)
                    break
                }
                case 'custom': {
                    let msgCont = JSON.parse(msg.content);
                    if (msgCont.type == 'invite') {
                        if (msgCont.accid == 0 || msgCont.accid == app.globalData.account) {
                            let inviteSource = this.data.inviteSource
                            if (inviteSource.length == 0) {
                                inviteSource.push(msgCont)
                                this.setData({
                                    inviteSource: inviteSource
                                })
                                return;
                            }
                            for (const key in inviteSource) {
                                console.log(inviteSource[key].company_uid == msgCont.company_uid);
                                if (inviteSource[key].company_uid == msgCont.company_uid) return;
                            }
                            console.log(123123123);
                            inviteSource.push(msgCont)
                            this.setData({
                                inviteSource: inviteSource
                            })
                            return;

                        }
                    } else {
                        self.addCompanyMsg(msg)
                    }
                    break
                }
            }
        })
        // 滚动到底部
        self.scrollToBottom()
    },
    /**
     * 添加通知消息到渲染队列中
     */
    addNotificationToRender(msg) {
        // 添加到渲染队列
        if (!msg.text) {
            return;
        }
        this.setData({
            hallNewsArr: [...this.data.hallNewsArr, {
                my: msg.from == app.globalData.account,
                account: msg.from,
                nick: msg.attach.fromNick,
                text: msg.text,
                type: msg.attach.type,
                nodes: []
            }]
        })

    },
    /**
     * 添加文本(包含emoji)消息到渲染队列中
     */
    addTextToRender(msg) {
        // 刷新界面
        if (!msg.text) {
            return;
        }
        this.setData({
            hallNewsArr: [...this.data.hallNewsArr, {
                my: msg.from == app.globalData.account,
                account: msg.from,
                nick: msg.fromNick,
                text: msg.text,
                type: msg.type,
                nodes: generateRichTextNode(msg.text)
            }]
        });
        this.scrollToBottom()
    },
    /**
     * 企业消息来电 加入中显示
     */
    addCompanyMsg(msg) {
        let msgCont = JSON.parse(msg.content);
        let msgData = {
            my: msg.from == app.globalData.account,
            account: msgCont.account,
            nick: msgCont.nick,
            text: msgCont.text,
            type: msgCont.type,
        };
        this.setData({
            hallNewsArr: [...this.data.hallNewsArr, msgData]
        });
        this.scrollToBottom();
    },
    /**
     * 滚动聊天内容到底部
     */
    scrollToBottom: function () {
        var len = this.data.hallNewsArr.length //遍历的数组的长度
        this.setData({
            scrollTop: 1000 * len // 这里我们的单对话区域最高1000，取了最大值，应该有方法取到精确的
        });
    },
    /**
     * 文本框输入事件
     */
    inputChange(e) {
        this.setData({
            inputValue: e.detail.value
        });
    },

    /**
     * 键盘单击发送，发送文本
     */
    inputSend(e) {
        this.setData({
            emojiShow: false,
        })
        this.sendRequest(this.data.inputValue);
    },
    /*
     * 发送网络请求：发送文本消息(包括emoji)
     */
    sendRequest(text) {
        let that = this;
        if (text == '') {
            showToast('text', '输入内容不能为空');
            return;
        }
        app.globalData.hallRoom.sendText({
            text,
            done: (err, msg) => {
                console.log("发送聊天室" + msg.type + "消息" + (!err ? "成功" : "失败") + ", id=" + msg.idClient, err, msg);
                if (err) {
                    console.log(err)
                    return
                }
                that.setData({
                    inputValue: ''
                })
                // 刷新界面
                that.addTextToRender(msg)
                // 滚动到底部
                that.scrollToBottom()
            }
        })
    },
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        clearInterval(this.Heart);
        clearInterval(this.gercompany)
        console.log('-------->退出聊天室');
        app.globalData.hallRoom.disconnect();
    },

    /**
     * 暂未完善
     */
    maintain() {
        showToast('text', '正在努力开发中，请等待后续版本更新。')
    },
    /**
     * ----------------------------->页面操作逻辑<------------------------
     */


    /**
     * 弹窗选择第几个显示
     * @param {穿参第几个} e 
     */
    popupTitleSelect(e) {
        let index = e.currentTarget.dataset.index
        if (this.popupVal !== index) {
            this.setData({
                popupVal: index
            })
        }
    },
    /**
     * 招聘信息详情弹窗切换
     */
    lookRecruitCont(e) {
        const {
            index,
            showval
        } = e.target.dataset

        if (showval) {
            let newWorkSource = this.data.recruitSource[index]
            this.setData({
                workSource: newWorkSource,
                recruitShow: true
            })
        } else {
            this.setData({
                recruitShow: false
            })
        }

    },
    /**
     * 房间分享
     */
    onShareAppMessage() {
        let {
            hallId,
            hallRoomId,
            meetingSource
        } = this.data
        return {
            title: `我正在参加${meetingSource.name}，快跟我一起组队刷offer吧！`,
            imageUrl: `${this.data.WEBURL}wxapp/img_room_share1.png`,
            path: `/pages/shareLogin/shareLogin?type=shareHallRoom&hallId=${hallId}&hallRoomId=${hallRoomId}`,
            success: function (res) {
                showToast('text', '分享成功')
            }
        }
    },
    /**
     * 表情添加
     */
    emojiAdd(e) {
        console.log('hall', e);
        this.setData({
            inputValue: this.data.inputValue + e.detail.emoji
        })
    },
    /**
     * 表情显示隐藏控制
     */
    emojiClick() {
        this.setData({
            emojiShow: !this.data.emojiShow
        })
    },
    /**
     * 删除邀请信息
     */
    inviteDel() {
        let inviteSource = this.data.inviteSource
        inviteSource.splice(0, 1)
        this.setData({
            inviteSource: inviteSource
        })
    },
    /**
     * 邀请进入房间
     */
    inviteGo() {
        var startTime = new Date(this.data.meetingSource.start_time);
        var currentTime = Date.parse(new Date());
        if (Date.parse(startTime) > currentTime) {
            showToast('text', '招聘会暂未开场');
            return;
        }
        if (!this.isPerfectInfo) {
            wx.showModal({
                title: '操作提示',
                content: '简历还没有完善，请完善简历后重试',
                success(res) {
                    if (res.confirm) {
                        wx.navigateTo({
                            url: '/studentMine/setUserInfo/setUserInfo'
                        })
                    }
                }
            })
            return;
        }
        let data = {
            token: wx.getStorageSync("token"),
            company_uid: this.data.inviteSource[0].company_uid,
        };
        ajaxPost("/company/companyInfo", data, (res) => {
            if (res.code == 0) {
                console.log('res===>', res);
                if (res.data.company_data.is_online == 0) {
                    showToast('text', '招聘者暂时不在，请稍后再试');
                    return;
                }
                if (res.data.student_count >= 10) {
                    showToast('text', '该房间以爆满，请选择其他房间重试');
                    return;
                }
                let inviteSource = this.data.inviteSource
                let companyid = inviteSource[0].company_uid
                inviteSource.splice(0, 1)
                this.setData({
                    inviteSource: inviteSource
                })
                wx.navigateTo({
                    url: '/pages/student/smallRoom/smallRoom?id=' + this.data.hallId + '&hallRoomId=' + this.data.hallRoomId + '&companyid=' + companyid
                })
            } else {
                showToast('text', res.msg)
            }
        });
    },
    /**
     * form 弹出层处理
     */
    formShowSelect(e) {
        app.globalData.fromShowVal = false
        this.setData({
            formShow: true
        })
        if (e.detail.formId == 'the formId is a mock one') {
            return
        }
        ajaxPost('/index/saveFormId', {
            form_id: e.detail.formId
        }, res => {})
    }
})